<template>
  <el-dialog
    v-model="store.isVisible"
    :title="t('Select signed signal')"
    width="500px"
    @close="store.cancel()"
  >
    <!-- 搜索框 -->
    <el-row :gutter="8" style="align-items: center; margin-bottom: 16px;">
      <el-col :span="24">
        <el-input
          v-model="store.searchKey"
          :placeholder="t('Search...')"
          spellcheck="false"
        />
      </el-col>
    </el-row>

    <el-card>
      <!-- 树形视图 -->
      <el-row>
        <el-tree
          ref="treeRef"
          :data="store.treeData"
          :props="{ children: 'children', label: 'name' }"
          node-key="id"
          :highlight-current="true"
          :default-expanded-keys="defaultExpandedKeys"
          style="width: 100%; height: 400px; overflow-y: auto;"
          @node-click="(data, node) => handleNodeClick(data, node)"
        >
          <template #default="{ node, data }">
            <span 
              :style="{ 
                color: data.exist === true ? 'var(--el-color-success)' : data.exist === false ? 'var(--el-color-primary)' : 'inherit',
                userSelect: 'none'
              }"
            >
              {{ data.name }}
            </span>
          </template>
        </el-tree>
      </el-row>

      <!-- 数值设置 -->
      <el-row :gutter="8" style="align-items: center;" v-if="store.showScaleSetting">
        <el-col :span="4">
          <span>{{ t('Value x') }}</span>
        </el-col>
        <el-col :span="16">
          <el-input
            v-model="store.signalScale"
            type="number"
            :placeholder="'1.0'"
            :precision="8"
            :step="0.1"
          />
        </el-col>
        <el-col :span="4">
          <span>{{ store.signalUnit }}</span>
        </el-col>
      </el-row>

      <!-- 符号位信号设置 -->
      <el-row :gutter="8" style="align-items: center;">
        <el-col :span="6">
          <span>{{ t('Sign bit signal:') }}</span>
        </el-col>
        <el-col :span="18">
          <el-button 
            type="primary" 
            link 
            @click="store.chooseSignBitSignal"
            style="padding: 0; text-align: left;"
          >
            {{ store.signBitSignalName || t('(Not configured)') }}
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <template #footer>
      <el-button 
        type="danger" 
        @click="store.deleteSignal"
        :disabled="!store.showDeleteButton"
        v-if="store.showDeleteButton">
        {{ t('Delete') }}
      </el-button>
      <el-button 
        type="primary" 
        @click="() => handleConfirm()"
        :disabled="isConfirmDisabled">
        {{ t('OK') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { useSignedSignalChooserStore } from '@/stores/signedSignalChooser'
import { useLanguageStore } from '@/stores/language'
import { ref, computed } from 'vue'

const store = useSignedSignalChooserStore()
const languageStore = useLanguageStore()
const treeRef = ref(null)

let clickCount = 0
let clickTimer = null

// 翻译函数
const t = (key) => {
  const translations = {
    'Select signed signal': {
      'en': 'Select signed signal',
      'zh': '选择带符号信号'
    },
    'Search...': {
      'en': 'Search...',
      'zh': '搜索...'
    },
    'Value x': {
      'en': 'Value x',
      'zh': '数值 x'
    },
    'Sign bit signal:': {
      'en': 'Sign bit signal:',
      'zh': '符号位信号：'
    },
    '(Not configured)': {
      'en': '(Not configured)',
      'zh': '(未配置)'
    },
    'Delete': {
      'en': 'Delete',
      'zh': '删除'
    },
    'OK': {
      'en': 'OK',
      'zh': '确认'
    }
  }
  return translations[key]?.[languageStore.isChinese ? 'zh' : 'en'] || key
}

const defaultExpandedKeys = computed(() => {
  const expandedKeys = []
  
  function collectExpandedKeys(nodes) {
    for (const node of nodes) {
      if (node.expandChildren === true) {
        expandedKeys.push(node.id)
      }
      if (node.children && node.children.length > 0) {
        collectExpandedKeys(node.children)
      }
    }
  }
  
  collectExpandedKeys(store.treeData)
  return expandedKeys
})

const isConfirmDisabled = computed(() => {
  if (store.showScaleSetting) {
    const scale = parseFloat(store.signalScale)
    if (isNaN(scale) || scale === 0) {
      return true
    }
  }
  
  const currentNode = treeRef.value?.getCurrentNode()
  return !currentNode || 
         (currentNode.children && currentNode.children.length > 0)
})

function handleNodeClick(data, node) {
  clickCount++
  if (clickCount === 1) {
    clickTimer = setTimeout(() => {
      clickCount = 0
    }, 300)
  } else if (clickCount === 2) {
    clearTimeout(clickTimer)
    clickCount = 0
    if (!isConfirmDisabled.value) handleConfirm(data, node)
  }
}

function handleConfirm(data, node) {
  const selectedData = data || treeRef.value?.getCurrentNode()
  if (selectedData && !selectedData.children) {
    store.confirm(selectedData)
  }
}
</script>
